import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:get/get_state_manager/src/rx_flutter/rx_obx_widget.dart';
import 'package:mobile_vpn/common/ext/asset_ext.dart';
import 'package:mobile_vpn/theme/color_palettes.dart';

import '../../router/routers.dart';

class MemberPage extends StatefulWidget {
  @override
  _MemberPageState createState() => _MemberPageState();
}

class _MemberPageState extends State<MemberPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final List<String> _tabs = ['铂金会员', '青铜会员', '更多'];
  final Rx<MemberItem?> _selectedMemberItem = Rx<MemberItem?>(null);
  final Rx<String> _selectedPaymentMethod = 'wechat'.obs;
  final RxInt _currentTabIndex = 0.obs;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: _tabs.length, vsync: this)
      ..addListener(_handleTabSelection);

    _selectedMemberItem.value = platinumMembers[0];
  }

  void _handleTabSelection() {
    if (_tabController.indexIsChanging) return;

    _currentTabIndex.value = _tabController.index;
    if (_tabController.index == 0) {
      _selectedMemberItem.value = platinumMembers[0];
    } else if (_tabController.index == 1) {
      _selectedMemberItem.value = bronzeMembers[0];
    }
  }

  @override
  void dispose() {
    _tabController.removeListener(_handleTabSelection);
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        return Scaffold(
          backgroundColor: ColorPalettes.instance.background,
          appBar: AppBar(
            title: const Text('会员'),
            centerTitle: true,
            backgroundColor: Colors.transparent,
            elevation: 0,
            titleTextStyle: TextStyle(
              color: ColorPalettes.instance.firstText,
              fontSize: 36.w, // 响应式字体大小
              fontWeight: FontWeight.w500,
            ),
          ),
          body: CustomScrollView(
            slivers: [
              SliverToBoxAdapter(
                child: _buildTabBar(), // 将TabBar放入滚动区域
              ),

              SliverFillRemaining(
                child: TabBarView(
                  controller: _tabController,
                  children: [
                    _buildMemberContent(platinumMembers),
                    _buildMemberContent(bronzeMembers),
                    _buildMoreTabContent(),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  PreferredSizeWidget _buildTabBar() {
    return PreferredSize(
      preferredSize: Size.fromHeight(60.h),
      child: Container(
        decoration: BoxDecoration(
          border: Border(bottom: BorderSide(color: Colors.grey[200]!)),
        ),
        child: TabBar(
          controller: _tabController,
          labelColor: Color(0xFFBB6080), // 统一选中标签颜色（玫红色）
          unselectedLabelColor: Colors.grey,  // 统一未选中标签颜色
          indicatorColor: Color(0xFFBB6080), // 统一指示器颜色
          indicatorWeight: 3.h,
          indicatorSize: TabBarIndicatorSize.tab,  // 修改为 TabBarIndicatorSize.tab
          indicatorPadding: EdgeInsets.symmetric(horizontal:  30.w),
          tabs: _tabs.map((tab)  => Tab(
            child: Text(
              tab,
              style: TextStyle(
                fontSize: 28.sp,
                fontWeight: FontWeight.w500,
              ),
            ),
          )).toList(),
        ),
      ),
    );
  }
  Widget _buildMemberContent(List<MemberItem> members) {
    return Column(
      children: [
        SizedBox(height: 30.h),
        _buildMemberCards(members),
        Obx(() => _selectedMemberItem.value != null
            ? _buildPaymentSection()
            : SizedBox.shrink()),
      ],
    );
  }

  Widget _buildMemberCards(List<MemberItem> members) {
    return SizedBox(
      height: 280.h,
      child: ScrollConfiguration(
        // 正确的参数名称是 'behavior' 而不是 'scrollBehavior'
        behavior: ScrollConfiguration.of(context).copyWith(
          dragDevices: {
            PointerDeviceKind.touch,
            PointerDeviceKind.mouse,
            PointerDeviceKind.stylus,
            PointerDeviceKind.trackpad,
          },
          scrollbars: false,
        ),
        child: ListView.builder(
          scrollDirection: Axis.horizontal,
          padding: EdgeInsets.symmetric(horizontal: 30.w),
          clipBehavior: Clip.none,
          itemCount: members.length,
          physics: const BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics()),
          itemBuilder: (context, index) {
            return Padding(
              padding: EdgeInsets.only(right: 30.w),
              child: Transform.translate(
                offset: Offset(0, 12.h),
                child: _buildMemberCard(members[index]),
              ),
            );
          },
        ),
      ),
    );
  }

  Widget _buildMemberCard(MemberItem member) {
    return GestureDetector(
      onTap: () => _selectedMemberItem.value = member,
      child: Stack(
        clipBehavior: Clip.none,
        children: [
          Container(
            width: 260.w,
            padding: EdgeInsets.symmetric(vertical: 25.h, horizontal: 20.w),
            decoration: BoxDecoration(
              border: Border.all(
                color: member.type == "1"
                    ? Color(0xFFCA7A95)
                    : Color(0xFF2F84E2),
                width: 3.w,
              ),
              borderRadius: BorderRadius.circular(20.r),
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  member.title,
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 34.sp,
                    color: Colors.black87,
                  ),
                ),
                SizedBox(height: 20.h),
                Text(
                  "USD ${member.price}",
                  style: TextStyle(
                    color: member.type == "1"
                        ? Color(0xFFBB6080)
                        : Color(0xFF2F84E2),
                    fontSize: 30.sp,
                  ),
                ),
                SizedBox(height: 10.h),
                Text(
                  '折合 USD ${(member.price / 30).toStringAsFixed(1)}/天',
                  style: TextStyle(
                    color: member.type == "1"
                        ? Color(0xFFBB6080)
                        : Color(0xFF2F84E2),
                    fontSize: 22.sp,
                  ),
                ),
              ],
            ),
          ),
          Positioned(
            left: 4.h,
            top: 4.h  ,
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 15.w, vertical: 7.h),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(20.r),
                  bottomRight: Radius.circular(20.r),
                ),
                color: member.type == "1"
                    ? Color(0xFFFAEFF3)
                    : Color(0xFFE6F4FF),
              ),
              child: Text(
                member.discount,
                style: TextStyle(
                  color: member.type == "1"
                      ? Color(0xFFBB6080)
                      : Color(0xFF2F84E2),
                  fontSize: 18.sp,
                ),
              ),
            ),
          ),
          Positioned(
            top: -12.h,
            left: 100.w,
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 4.h),
              decoration: BoxDecoration(
                color: Color(0xFFFD0105),
                borderRadius: BorderRadius.circular(15.r),
              ),
              constraints: BoxConstraints(minWidth: 100.w),
              child: Center(
                child: Text(
                  "额外送7天",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 18.sp,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget _buildPaymentSection() {
    return Expanded(
      child: SingleChildScrollView(
        child: Column(
          children: [
            SizedBox(height: 40.h),
            _buildSelectedPlanCard(),
            SizedBox(height: 40.h),
            _buildPaymentMethods(),
            SizedBox(height: 50.h),
            _buildSubscribeButton(),
            SizedBox(height: 30.h),
            _buildCustomerSupportText(),
          ],
        ),
      ),
    );
  }

  Widget _buildSelectedPlanCard() {
    return Obx(() {
      if (_selectedMemberItem.value == null) return SizedBox.shrink();

      final member = _selectedMemberItem.value!;
      return Container(
        width: double.infinity,
        margin: EdgeInsets.symmetric(horizontal: 30.w),
        padding: EdgeInsets.symmetric(vertical: 30.h, horizontal: 20.w),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(20.r),
          boxShadow: [
            BoxShadow(
              color: Colors.grey.withOpacity(0.1),
              blurRadius: 15.r,
              offset: Offset(0, 5.h),
            ),
          ],
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.verified_rounded,
                  color: member.type == "1"
                      ? Color(0xFFBB6080)
                      : Color(0xFF2F84E2),
                  size: 36.sp,
                ),
                SizedBox(width: 10.w),
                Text(
                  '${_tabs[_tabController.index]}  · ${member.title}',
                  style: TextStyle(
                    fontSize: 32.sp,
                    fontWeight: FontWeight.bold,
                    color: Colors.black87,
                  ),
                ),
              ],
            ),
            SizedBox(height: 25.h),
            Text(
              'USD ${member.price}',
              style: TextStyle(
                fontSize: 44.sp,
                fontWeight: FontWeight.w900,
                color: member.type == "1"
                    ? Color(0xFFBB6080)
                    : Color(0xFF2F84E2),
              ),
            ),
            SizedBox(height: 15.h),
            Text(
              '≈ ${(member.price / 30).toStringAsFixed(1)}/天',
              style: TextStyle(
                fontSize: 26.sp,
                color: Colors.grey[600],
              ),
            ),
          ],
        ),
      );
    });
  }

  Widget _buildPaymentMethods() {
    return Column(
      children: [
        _buildPaymentMethodCard(
          icon: "wechatpay".png,
          title: "微信支付",
          value: 'wechat',
        ),
        _buildPaymentMethodCard(
          icon: "alipaypayment".png,
          title: "支付宝",
          value: 'alipay',
        ),
      ],
    );
  }

  Widget _buildPaymentMethodCard({
    required String icon,
    required String title,
    required String value,
  }) {
    return Card(
      margin: EdgeInsets.zero,
      elevation: 2,
      color: Color(0xFFFFFFFF),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.zero),
      child: Obx(() {
        final member = _selectedMemberItem.value;
        return Padding(
          padding: EdgeInsets.all(20.h),
          child: Row(
            children: [
              Image.asset(
                icon,
                width: 60.w,
                height: 60.h,
              ),
              SizedBox(width: 20.w),
              Text(
                title,
                style: TextStyle(
                  fontSize: 32.sp,
                  fontWeight: FontWeight.w500,
                ),
              ),
              Spacer(),
              Radio<String>(
                value: value,
                groupValue: _selectedPaymentMethod.value,
                onChanged: (v) => _selectedPaymentMethod.value = v!,
                fillColor: WidgetStateProperty.resolveWith<Color>((states) {
                  if (member == null) return Color(0xFF009FE8);
                  return member.type == "1"
                      ? Color(0xFFBB6080)
                      : Color(0xFF2F84E2);
                }),
              ),
            ],
          ),
        );
      }),
    );
  }

  Widget _buildSubscribeButton() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 50.w),
      child: ElevatedButton(
        onPressed: () {},
        style: ElevatedButton.styleFrom(
          backgroundColor: Color(0xFF009FE8),
          minimumSize: Size(double.infinity, 90.h),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(45.r),
          ),
          elevation: 3,
        ),
        child: Text(
          '立即开通',
          style: TextStyle(
            fontSize: 34.sp,
            fontWeight: FontWeight.w600,
            color: Colors.white,
          ),
        ),
      ),
    );
  }

  Widget _buildCustomerSupportText() {
    return Container(
      padding: EdgeInsets.only(bottom: 30.h),
      child: Text.rich(
        TextSpan(
          children: [
            TextSpan(
              text: "支付遇到问题？联系",
              style: TextStyle(
                fontSize: 26.sp,
                color: Colors.grey[600],
              ),
            ),
            TextSpan(
              text: "在线客服",
              style: TextStyle(
                fontSize: 26.sp,
                color: Colors.blue,
                fontWeight: FontWeight.w500,
                decoration: TextDecoration.underline,
              ),
              recognizer: TapGestureRecognizer()
                ..onTap = () => AppRoutes.jumpPage(AppRoutes.contactServerPage),
            ),
            TextSpan(
              text: "获取帮助",
              style: TextStyle(
                fontSize: 26.sp,
                color: Colors.grey[600],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildMoreTabContent() {
    return SingleChildScrollView(
      physics: AlwaysScrollableScrollPhysics(),
      padding: EdgeInsets.only(bottom: 30.h),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [

          SizedBox(height: 20.h),
          Column(
            children: [
              _buildVerticalMemberCard(
                title: "VIP 体验会员",
                price: 30,
                discount: "1.0折",
                type: "1",
                description: "体验7天VIP服务，限时优惠！",
              ),
              _buildVerticalMemberCard(
                title: "年度超级会员",
                price: 800,
                discount: "5.5折",
                type: "2",
                description: "全年畅享所有特权，超值推荐！",
              ),
              _buildVerticalMemberCard(
                title: "季度尊享会员",
                price: 250,
                discount: "6.5折",
                type: "1",
                description: "季度专属优惠，不容错过！",
              ),
            ],
          ),
          SizedBox(height: 30.h),
        ],
      ),
    );
  }



// 修改 _buildVerticalMemberCard 方法
  Widget _buildVerticalMemberCard({
    required String title,
    required double price,
    required String discount,
    required String type,
    required String description,
  }) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal:  30.w, vertical: 10.h),
      child: GestureDetector(
        onTap: () =>(
            AppRoutes.jumpPage(AppRoutes.memberExtensionPage)
        ),
        child: Card(
          color: ColorPalettes.instance.background,
          elevation: 4,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.r)),
          child: Container(
            padding: EdgeInsets.all(20.h),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      title,
                      style: TextStyle(
                        fontSize: 32.sp,
                        fontWeight: FontWeight.bold,
                        color: type == "1"
                            ? Color(0xFFBB6080)
                            : Color(0xFF2F84E2),
                      ),
                    ),
                    Text(
                      "USD $price",
                      style: TextStyle(
                        fontSize: 28.sp,
                        fontWeight: FontWeight.bold,
                        color: type == "1"
                            ? Color(0xFFBB6080)
                            : Color(0xFF2F84E2),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 10.h),
                Text(
                  description,
                  style: TextStyle(
                    fontSize: 22.sp,
                    color: Colors.grey[600],
                  ),
                ),
                SizedBox(height: 15.h),
                Text(
                  "折合 USD ${(price / 30).toStringAsFixed(1)}/天",
                  style: TextStyle(
                    fontSize: 20.sp,
                    color: Colors.grey[500],
                  ),
                ),
                SizedBox(height: 15.h),
                Container(
                  padding: EdgeInsets.symmetric(horizontal:  15.w, vertical: 7.h),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(15.r),
                    color: type == "1"
                        ? Color(0xFFFAEFF3)
                        : Color(0xFFE6F4FF),
                  ),
                  child: Text(
                    discount,
                    style: TextStyle(
                      fontSize: 18.sp,
                      color: type == "1"
                          ? Color(0xFFBB6080)
                          : Color(0xFF2F84E2),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  final List<MemberItem> platinumMembers = [
    MemberItem(title: "1个月", price: 120, discount: "5.0折", type: "1"),
    MemberItem(title: "3个月", price: 300, discount: "4.2折", type: "1"),
    MemberItem(title: "12个月", price: 960, discount: "3.5折", type: "1"),
  ];

  final List<MemberItem> bronzeMembers = [
    MemberItem(title: "1个月", price: 80, discount: "3.0折", type: "2"),
    MemberItem(title: "3个月", price: 200, discount: "2.5折", type: "2"),
    MemberItem(title: "12个月", price: 600, discount: "2.0折", type: "2"),
  ];
}

class MemberItem {
  final String title;
  final double price;
  final String discount;
  final String type;

  MemberItem({
    required this.title,
    required this.price,
    required this.discount,
    required this.type,
  });
}